package multiconnector.broadcast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;

import android.util.Log;

public class SenderSocket extends BroadcastSocket {

	private static final String LOG_TAG = SenderSocket.class.getName();
	private ArrayList<DatagramPacket> mQueue = new ArrayList<DatagramPacket>();

	public SenderSocket(InetAddress inetAddress, int port) {
		super(inetAddress, port);
	}


	public void run() {
		while (isRunning()) {
			synchronized (mQueue) {
				// is queue empty?
				if (mQueue.size() == 0)
					continue;

				Log.d(LOG_TAG, "sender fires");

				// send next item in queue
				DatagramPacket packet = mQueue.remove(0);
				Log.d(LOG_TAG, "send " + new String(packet.getData()));
				try {
					getSocket().send(packet);
				} catch (IOException e) {
					Log.e(LOG_TAG, "exception while sending", e);
				}
			}
		}
	}

	public void send(String pMessage, int pPort) {
		// build packet
		byte[] message = pMessage.getBytes();
		DatagramPacket packet = new DatagramPacket(message, message.length,
				getBroadcastAddress(), pPort);

		// add packet to queue
		synchronized (mQueue) {
			mQueue.add(packet);
		}
	}

	@Override
	public DatagramSocket createSocket() throws SocketException {
		return new DatagramSocket();
	}

}
